package insta.project.player;

import insta.project.CoverFlow;
import insta.project.R;
import insta.project.SongsActivity;
import insta.project.remote.RemoteAudioFactory;
import insta.project.utils.ImageHelper;
import insta.project.utils.StringHelper;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader.TileMode;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.SeekBar;
import android.widget.TextView;

/**
 * Play Music
 * 
 * @author candy
 * 
 */
public class PlayMusicCoverflowActivity extends Activity implements
		SeekBar.OnSeekBarChangeListener, OnBufferingUpdateListener,
		OnCompletionListener {

	private MediaPlayer mMediaPlayer;
	private int position;
	private int iCoverflowPosition = 0;
	private Audio currentAudio;

	SeekBar mSeekBar;
	TextView mProgressText;
	TextView mTrackingText;
	ImageView mPlayPause;
	private Handler mHandler = new Handler();

	private CoverFlow cf;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.playmusiccoverflow);

		position = this.getIntent().getExtras().getInt("position");
		currentAudio = new Audio();
		currentAudio.setFilename(this.getIntent().getStringExtra("audio_data"));
		currentAudio.setTitle(this.getIntent().getStringExtra("audio_title"));
		currentAudio.setArtist(this.getIntent().getStringExtra("audio_artist"));
		currentAudio
				.setImageuri(this.getIntent().getStringExtra("audio_image"));

		display(currentAudio);

		RemoteAudioFactory remoteAdapter = new RemoteAudioFactory(this);

		SongsActivity.createImageList();
		cf = (CoverFlow) findViewById(R.id.cf);
		cf.setAdapter(new CoverFlowAdapter(SongsActivity.imageList, this));

		// *********************************** //
		// ******* DISPLAY RATINGBAR ********* //
		// *********************************** //

		// final RatingBar ratingbar = (RatingBar) findViewById(R.id.ratingbar);
		// Log.d("rating bar", "" + ratingbar);

		// ratingbar.setFocusable(false);
		// necessaire pour activer le onclick item
		// ratingbar
		// .setOnRatingBarChangeListener(new
		// RatingBar.OnRatingBarChangeListener() {
		// public void onRatingChanged(RatingBar ratingBar,
		// float rating, boolean fromUser) {
		// ratingbar.setRating(rating);
		// Toast.makeText(PlayMusicActivity.this,
		// "rating:" + String.valueOf(rating),
		// Toast.LENGTH_LONG).show();
		// }
	}

	public void display(Audio _audio) {
		/*
		 * ImageView jaquette = (ImageView) findViewById(R.id.avatar); if
		 * (_audio.getImageuri() != null) {
		 * jaquette.setImageURI(Uri.parse(_audio.getImageuri())); } else {
		 * jaquette.setImageResource(R.drawable.default_cover); }
		 */

		TextView title = (TextView) findViewById(R.id.title);
		title.setText(_audio.getTitle());

		TextView artist = (TextView) findViewById(R.id.artist);
		artist.setText(_audio.getArtist());

		mPlayPause = (ImageView) findViewById(R.id.playpause);

		mProgressText = (TextView) findViewById(R.id.progress);
		mTrackingText = (TextView) findViewById(R.id.tracking);

		mMediaPlayer = new MediaPlayer();
		mMediaPlayer.setOnBufferingUpdateListener(this);
		mMediaPlayer.setOnCompletionListener(this);

		try {
			if (mMediaPlayer.isPlaying()) {
				mMediaPlayer.reset();
			}
			mMediaPlayer.setDataSource(_audio.getFilename());
			mMediaPlayer.prepare();

			mSeekBar = (SeekBar) findViewById(R.id.seekbar);
			mSeekBar.setMax(mMediaPlayer.getDuration());
			mSeekBar.setOnSeekBarChangeListener(this);

			mMediaPlayer.start();
			primarySeekBarProgressUpdater();
			mPlayPause.setImageResource(R.drawable.pause);
			mPlayPause.setTag("play");

		} catch (Exception e) {

		}
	}

	/**
	 * Method which updates the SeekBar primary progress by current song playing
	 * position
	 */
	private void primarySeekBarProgressUpdater() {
		mSeekBar.setProgress(mMediaPlayer.getCurrentPosition());
		if (mMediaPlayer.isPlaying()) {
			Runnable notification = new Runnable() {
				public void run() {
					primarySeekBarProgressUpdater();
				}
			};
			mHandler.postDelayed(notification, 1000);
		}
	}

	public void onBackPressed() {
		super.onBackPressed();
		Log.d("playMusicCoverflow", "backpress");
		mMediaPlayer.stop();
		finish();
	}

	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromTouch) {
		if (fromTouch) {
			mMediaPlayer.seekTo(progress);
			seekBar.setProgress(progress);
		}
	}

	public void onStartTrackingTouch(SeekBar seekBar) {
		seekBar.setSecondaryProgress(seekBar.getProgress());
		mTrackingText.setText("trackingOn");
	}

	public void onStopTrackingTouch(SeekBar seekBar) {
		mTrackingText.setText("trackingoff");
	}

	public void onClickPlayPause(View v) {
		switch (v.getId()) {
		case R.id.playpause:
			if (mPlayPause.getTag().equals("pause")) {
				mPlayPause.setTag("play");
				mMediaPlayer.start();
				primarySeekBarProgressUpdater();
				mPlayPause.setImageResource(R.drawable.pause);
			} else if (mPlayPause.getTag().equals("play")) {
				if (mMediaPlayer.isPlaying()) {
					mPlayPause.setTag("pause");
					mMediaPlayer.pause();
					mPlayPause.setImageResource(R.drawable.play);
				}
			}
			break;
		}
	}

	public void switchToNext() {
		position = (position + 1 < SongsActivity.musics.size()) ? position++
				: 0;
		currentAudio = SongsActivity.musics.get(position);
		display(currentAudio);
	}

	public void switchToPrevious() {
		position = (position > 0) ? position--
				: SongsActivity.musics.size() - 1;
		currentAudio = SongsActivity.musics.get(position);
		display(currentAudio);
	}

	public void switchToPosition(int _iPosition) {
		if (_iPosition != position) {
			position = _iPosition;

			currentAudio = SongsActivity.musics.get(position);

			mMediaPlayer.stop();
			currentAudio = SongsActivity.musics.get(position);
			display(currentAudio);

		}
	}

	public void onClick(View v) {

		boolean continue_move = false;

		switch (v.getId()) {
		case R.id.previous:
			Log.d("button_click", "previous");
			if (position > 0) {
				position--;
				continue_move = true;
			}
			break;
		case R.id.next:
			Log.d("PlayMusicCoverFlowActivity.nextTrack()", "next");
			if (position + 1 < SongsActivity.musics.size()) {
				position++;
				continue_move = true;
			}
			break;
		}

		if (continue_move) {
			mMediaPlayer.stop();
			currentAudio = SongsActivity.musics.get(position);
			display(currentAudio);
		}
	}

	public void onCompletion(MediaPlayer mp) {
		// Trying to get next song
		int nNextIndex = (this.position + 1 >= SongsActivity.musics.size()) ? 0
				: this.position + 1;
		Log.d("player.play", String.valueOf(nNextIndex));
		this.display(SongsActivity.musics.get(nNextIndex));

	}

	public void onBufferingUpdate(MediaPlayer mp, int percent) {
	}

	public int getCoverflowPosition() {
		return iCoverflowPosition;
	}

	public void setCoverflowPosition(int iCoverflowPosition) {
		this.iCoverflowPosition = iCoverflowPosition;
	}

	/*********************************************
	 * ADAPTER FOR COVERFLOW
	 */
	private class CoverFlowAdapter extends BaseAdapter {
		private String[] ressourcesId;
		private PlayMusicCoverflowActivity Parent;
		
		private Bitmap defaultCover = BitmapFactory.decodeResource(
				getResources(), R.drawable.default_cover);

		public CoverFlowAdapter(String[] ressourcesId,
				PlayMusicCoverflowActivity parentActivity) {
			this.ressourcesId = ressourcesId;
			this.Parent = parentActivity;
		}

		public int getCount() {
			return ressourcesId.length;
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			Log.d("PlayMusicCoverFlowActivity.getItemId()",
					"Item position is now " + position);
			this.Parent.switchToPosition(position);
			this.Parent.setCoverflowPosition(position);
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			Context c = PlayMusicCoverflowActivity.this;
			String currentImageResource = ressourcesId[position];
			Bitmap defaultInput = this.defaultCover;
			Bitmap input = null;
			/*
			 * If image is a path, call our getBitmap function, it will retreive
			 * image from sd card, or from a www url and store it on sdcard for
			 * caching purposes;
			 */
			if (!StringHelper.isNumeric(currentImageResource)
					|| Integer.parseInt(currentImageResource) != R.drawable.default_cover) {
				input = ImageHelper.getBitmapFromUri(currentImageResource,
						this.Parent.getContentResolver());
			}
			input = (input == null) ? defaultInput : input;

			Bitmap output = createReflectedImage(c, input);
			ImageView v = new ImageView(c);
			v.setLayoutParams(new Gallery.LayoutParams(output.getWidth(),
					output.getHeight()));
			v.setScaleType(ScaleType.FIT_XY);
			v.setImageBitmap(output);
			return v;
		}

		private Bitmap createReflectedImage(Context context,
				Bitmap originalImage) {
			// The gap we want between the reflection and the original image
			final int reflectionGap = 4;
			int width = originalImage.getWidth();
			int height = originalImage.getHeight();

			// This will not scale but will flip on the Y axis
			Matrix matrix = new Matrix();
			matrix.preScale(1, -1);

			// Create a Bitmap with the flip matrix applied to it.
			// We only want the bottom half of the image
			Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0,
					height / 2, width, height / 2, matrix, false);

			// Create a new bitmap with same width but taller to fit reflection
			Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
					(height + height / 2), Config.ARGB_8888);

			// Create a new Canvas with the bitmap that's big enough for
			// the image plus gap plus reflection
			Canvas canvas = new Canvas(bitmapWithReflection);
			// Draw in the original image
			canvas.drawBitmap(originalImage, 0, 0, null);
			// Draw in the gap
			Paint defaultPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
			canvas.drawRect(0, height, width, height + reflectionGap,
					defaultPaint);
			// Draw in the reflection
			canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);

			// Create a shader that is a linear gradient that covers the
			// reflection
			Paint paint = new Paint();
			LinearGradient shader = new LinearGradient(0,
					originalImage.getHeight(), 0,
					bitmapWithReflection.getHeight() + reflectionGap,
					0x70ffffff, 0x00ffffff, TileMode.CLAMP);
			// Set the paint to use this shader (linear gradient)
			paint.setShader(shader);
			// Set the Transfer mode to be porter duff and destination in
			paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
			// Draw a rectangle using the paint with our linear gradient
			canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
					+ reflectionGap, paint);

			return bitmapWithReflection;
		}
	}
}